<?php
namespace  Backend\Controller;
use Think\Controller;

class PassportController extends Controller
{
	
	public function login() {
		$this->display();
	}
	
	public function reg() {
		$this->display();
	}
	
    public function doLogin() {
        if(IS_POST) {
            $model = D('Admin');
            // 接收表单并且根据规则验证表单
            if($model->validate($model->_login_validate)->create() && $model->login()){
				session('Admin_Online', true);
                $this->ajaxReturn(['status' => 'success', 'jump'=>'/main/index', 'msg' => '登录成功！']);
            }
        }
		
		$this->ajaxReturn(['status' => 'failed', 'msg' =>'登录失败' ]);
    }
	
	public function doReg() {
		$model=D('Admin');
        $user =$model->where(array("username" => $_POST['username']))->find();

        if (!$user) {
            if (!$data = $model->create()) {
                $this->ajaxReturn(['status' => 'failed', 'msg' => $model->getError()]);
                exit;
            }

            $data['username']=I("post.username");
            $data['password']=md5(I("post.password")."dsp");


            if ($result = $model->add($data)) {

                $this->ajaxReturn(['status' => 'success', 'msg' => '恭喜注册成功！']);
                exit;
            } else {
                $this->ajaxReturn(['status' => 'failed', 'msg' => '注册失败!']);
                exit;
            }

        }else{
            $this->ajaxReturn(['status' => 'failed', 'msg' =>'注册失败，账号已经存在！']);
            exit;
        }
        
    }
	public  function account(){

        $this->display();
    }
    public  function account_manage(){
        $data=$_POST;
        $id = $_SESSION['id'];

        if($data['password'] == $data['confirm_password']) {

            $data['password'] =md5($data['password'].'dsp');
            $model = D('Admin');
            $result = $model->where(array('id' =>$id))->save($data);

            if ($result !== false) {
                $this->ajaxReturn(['status' => 'success', 'msg' => '修改成功！']);
                exit;
            } else {
                $this->ajaxReturn(['status' => 'failed', 'msg' => $model->getError()]);
            }


        } else {
            $this->ajaxReturn(['status' => 'failed', 'msg' => '两次密码不一致']);
        }


    }
	// 退出登录
    public function logout() {
        session('Admin_Online', null);
        redirect(U('/passport/login'));
    }
}